import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { MessageCircle, Heart, Clock, MapPin } from 'lucide-react';
import { useAuthStore, useMatchStore, useChatStore } from '../stores';
import { apiService } from '../services/api';
import toast from 'react-hot-toast';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import type { Match } from '../types/api';

const MatchesPage: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { matches, setMatches } = useMatchStore();
  const { unreadCounts, setUnreadCount } = useChatStore();
  const [isLoading, setIsLoading] = useState(true);

  // 获取匹配列表
  useEffect(() => {
    const fetchMatches = async () => {
      if (!user) return;

      try {
        const response = await apiService.getMatches(user.user_id, 1, 50);
        if (response.code === 0) {
          setMatches(response.data.matches);
        }
      } catch (error) {
        console.error('Fetch matches error:', error);
        toast.error('获取匹配列表失败');
      } finally {
        setIsLoading(false);
      }
    };

    fetchMatches();
  }, [user, setMatches]);

  // 获取未读消息数量
  useEffect(() => {
    const fetchUnreadCounts = async () => {
      if (!user || matches.length === 0) return;

      try {
        const response = await apiService.getUnreadMessageCount(user.user_id);
        if (response.code === 0) {
          // 这里需要根据实际API返回的数据结构来处理
          // 假设API返回的是每个匹配的未读数量
          matches.forEach(match => {
            setUnreadCount(match.match_id, 0); // 临时设置为0
          });
        }
      } catch (error) {
        console.error('Fetch unread counts error:', error);
      }
    };

    fetchUnreadCounts();
  }, [user, matches, setUnreadCount]);

  const handleChat = (match: Match) => {
    navigate(`/chat/${match.match_id}`);
  };

  const formatMatchTime = (timeString: string) => {
    try {
      return formatDistanceToNow(new Date(timeString), { 
        addSuffix: true, 
        locale: zhCN 
      });
    } catch {
      return '刚刚';
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">加载匹配列表中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 pt-20">
      <div className="max-w-md mx-auto px-4">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-6"
        >
          <h1 className="text-2xl font-bold text-gray-900">匹配</h1>
          <p className="text-gray-600">你已经有 {matches.length} 个匹配</p>
        </motion.div>

        {/* 匹配列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="space-y-4"
        >
          {matches.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-20 h-20 bg-gray-200 rounded-full mx-auto mb-4 flex items-center justify-center">
                <Heart className="text-gray-400" size={32} />
              </div>
              <h2 className="text-xl font-semibold text-gray-900 mb-2">还没有匹配</h2>
              <p className="text-gray-600 mb-6">去发现页面滑动卡片，找到你的心动对象</p>
              <button
                onClick={() => navigate('/home')}
                className="btn-primary"
              >
                开始发现
              </button>
            </div>
          ) : (
            matches.map((match, index) => (
              <motion.div
                key={match.match_id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.1 }}
                className="bg-white rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow duration-200"
              >
                <div className="flex items-center space-x-4">
                  {/* 头像 */}
                  <div className="relative">
                    <img
                      src={match.avatar || '/api/placeholder/60/60'}
                      alt={match.nickname}
                      className="w-16 h-16 rounded-full object-cover"
                    />
                    <div className="absolute -bottom-1 -right-1 w-5 h-5 bg-green-500 border-2 border-white rounded-full"></div>
                  </div>

                  {/* 用户信息 */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-1">
                      <h3 className="text-lg font-semibold text-gray-900 truncate">
                        {match.nickname}
                      </h3>
                      {unreadCounts[match.match_id] > 0 && (
                        <span className="bg-red-500 text-white text-xs rounded-full px-2 py-1 min-w-[20px] text-center">
                          {unreadCounts[match.match_id]}
                        </span>
                      )}
                    </div>
                    
                    <div className="flex items-center space-x-4 text-sm text-gray-500 mb-2">
                      <span className="flex items-center">
                        <Clock size={14} className="mr-1" />
                        {formatMatchTime(match.match_time)}
                      </span>
                      {match.location && (
                        <span className="flex items-center">
                          <MapPin size={14} className="mr-1" />
                          {match.location}
                        </span>
                      )}
                    </div>

                    {/* 共同兴趣 */}
                    {match.interests && match.interests.length > 0 && (
                      <div className="flex flex-wrap gap-1 mb-2">
                        {match.interests.slice(0, 3).map((interest) => (
                          <span
                            key={interest.tag_id}
                            className="px-2 py-1 bg-primary-100 text-primary-700 rounded-full text-xs"
                          >
                            {interest.tag_name}
                          </span>
                        ))}
                        {match.interests.length > 3 && (
                          <span className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs">
                            +{match.interests.length - 3}
                          </span>
                        )}
                      </div>
                    )}

                    {/* 个人简介 */}
                    {match.bio && (
                      <p className="text-sm text-gray-600 line-clamp-2">
                        {match.bio}
                      </p>
                    )}
                  </div>

                  {/* 聊天按钮 */}
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => handleChat(match)}
                    className="w-12 h-12 bg-primary-500 hover:bg-primary-600 rounded-full flex items-center justify-center transition-colors duration-200"
                  >
                    <MessageCircle className="text-white" size={20} />
                  </motion.button>
                </div>
              </motion.div>
            ))
          )}
        </motion.div>

        {/* 底部提示 */}
        {matches.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.5 }}
            className="text-center mt-8 pb-8"
          >
            <p className="text-gray-500 text-sm">
              点击聊天按钮开始对话，或者继续发现更多朋友
            </p>
          </motion.div>
        )}
      </div>
    </div>
  );
};

export default MatchesPage;
